var SoftRenderer;
(function (SoftRenderer) {
    var Device = (function () {
        function Device(canvas) {
            this.canvas = canvas;
            this.width = canvas.width;
            this.height = canvas.height;
            this.context2d = canvas.getContext("2d");
            this.depthBuffer = new Array(this.width * this.height);
        }
        Device.prototype.clear = function () {
            this.context2d.clearRect(0, 0, this.width, this.height);
            this.backbufferImage = this.context2d.getImageData(0, 0, this.width, this.height);
            this.backbufferData = this.backbufferImage.data;
            for (var i = 0; i < this.depthBuffer.length; i++) {
                this.depthBuffer[i] = 10000000;
            }
        };
        Device.prototype.present = function () {
            this.context2d.putImageData(this.backbufferImage, 0, 0);
        };
        Device.prototype.putPixel = function (x, y, z, color, depthTest, depthWrite) {
            if (depthTest === void 0) { depthTest = true; }
            if (depthWrite === void 0) { depthWrite = true; }
            // convert float to integer
            x = (x >> 0);
            y = (y >> 0);
            if (x < 0 || x >= this.width || y < 0 || y >= this.height) {
                return;
            }
            var index = x + y * this.width;
            if (true === depthTest) {
                if (this.depthBuffer[index] < z)
                    return; // Discard
            }
            // As we have a 1-D Array for our back buffer
            // we need to know the equivalent cell index in 1-D based
            // on the 2D coordinates of the screen
            var index4 = index * 4;
            // RGBA color space is used by the HTML5 canvas
            this.backbufferData[index4] = color.r * 255;
            this.backbufferData[index4 + 1] = color.g * 255;
            this.backbufferData[index4 + 2] = color.b * 255;
            this.backbufferData[index4 + 3] = color.a * 255;
            if (true === depthWrite) {
                this.depthBuffer[index] = z;
            }
        };
        return Device;
    })();
    SoftRenderer.Device = Device;
})(SoftRenderer || (SoftRenderer = {}));
